package org.example.config;

import cn.hutool.core.date.DateUtil;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.Chunk;
import org.example.domain.FileResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Date;

@Slf4j
@Component
public class FileConfig {

    private static final String  filePath = "d:/";


    public int postFileUpload(Chunk chunk, String deptName) {
        MultipartFile file = chunk.getFile();
        log.debug("file originName: {}, chunkNumber: {}", file.getOriginalFilename(), chunk.getChunkNumber());
        //文件上传路径
        String filePath = generatePath(chunk, deptName);
        log.info("chunk file path :{}", filePath);
        Path path = Paths.get(filePath);
        //判断文件是否存在
        if (Files.exists(path)) {
            return CommonConstant.UPDATE_EXISTS;
        }
        //上传文件
        try {
            Files.write(path, chunk.getFile().getBytes());
            return CommonConstant.UPDATE_SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            return CommonConstant.UPDATE_FAIL;

        }
    }

    public static void main(String[] args) {
        String year = DateUtil.year(new Date()) + "";
        String month = DateUtil.month(new Date())+1 + "";
        String day = DateUtil.dayOfMonth(new Date()) + "";
        System.out.println(year+month+day);

    }
    private String generatePath(Chunk chunk, String deptName) {
        String year = DateUtil.year(new Date()) + "";
        String month = DateUtil.month(new Date())+1 + "";
        String day = DateUtil.dayOfMonth(new Date()) + "";
        //上传目录，读取属性配置
        String path = filePath + deptName + "/" + year + "/" + month + "/" + day + "/";
        System.out.println("上传时的文件为"+path);
        //StringBuilder拼接，效率高
        StringBuilder sb = new StringBuilder();
        //文件夹地址/md5
        sb.append(path).append("/").append(chunk.getIdentifier()).append("/");
        //判断uploadFolder/identifier 路径是否存在，不存在则创建
        if (!Files.isWritable(Paths.get(sb.toString()))) {
            log.info("path not exist,create path: {}", sb.toString());
            try {
                Files.createDirectories(Paths.get(sb.toString()));
            } catch (IOException e) {
//                log.error(e.getMessage(), e);
            }
        }
        //文件夹地址/md5/文件名-1
        return sb.append(chunk.getFilename())
                .append("-")
                .append(chunk.getChunkNumber()).toString();
    }


    /**
     * 合并文件
     *
     * @param chunk
     * @return
     */
    public FileResult mergeFile(Chunk chunk, String deptName) {
        String filename = chunk.getFilename();
        String year = DateUtil.year(new Date()) + "";
        String month = DateUtil.month(new Date())+1 + "";
        String day = DateUtil.dayOfMonth(new Date()) + "";
        //上传目录，读取属性配置
        String path = filePath + deptName + "/" + year + "/" + month + "/" + day + "/";
        String file = path + chunk.getIdentifier() + "/" + filename;
        String folder = path + chunk.getIdentifier();
        //文件合并
        merge(file, folder, filename);
        System.out.println("现在的文件路径是"+path);
        //上传目录，读取属性配置
        String fileName = chunk.getIdentifier() + "/" + filename;
        String fileUrl = path +chunk.getIdentifier() + "/" + filename;

        return new FileResult().setDomain("http://localhost:8082/").setFileUrl(fileUrl).setFileName(fileName);
    }

    /**
     * 文件合并
     * @param targetFile 要形成的文件名
     * @param folder     要形成的文件夹地址
     * @param filename   文件的名称
     */
    private void merge(String targetFile, String folder, String filename) {
        try {
            Files.createFile(Paths.get(targetFile));
            Files.list(Paths.get(folder))
                    .filter(path -> !path.getFileName().toString().equals(filename))
                    .sorted((o1, o2) -> {
                        String p1 = o1.getFileName().toString();
                        String p2 = o2.getFileName().toString();
                        int i1 = p1.lastIndexOf("-");
                        int i2 = p2.lastIndexOf("-");
                        return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
                    })
                    .forEach(path -> {
                        try {
                            //以追加的形式写入文件
                            Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
                            //合并后删除该块
                            Files.delete(path);
                        } catch (IOException e) {
                            log.error(e.getMessage(), e);
                        }
                    });
        } catch (IOException e) {
//            log.error(e.getMessage(), e);
        }
    }

}
